import  random
import tkinter as tk
import shutil, os, threading, requests, re, time
import tkinter.messagebox as messagebox
import tkinter.filedialog
from tkinter import ttk
from fake_useragent import UserAgent
import hashlib
from tkinter import *
import winshell

class proxy_get(tk.Toplevel):
    def __init__(self,base):
        super().__init__()
        self.title('设置:')
        self.w, self.h = self.maxsize()
        self.a = 217
        self.b = 350
        self.x = (self.w - self.a) / 2
        self.y = (self.h - self.b) / 2
        self.wm_resizable(False, False)
        self.geometry('%dx%d+%d+%d' % (self.a, self.b, self.x, self.y))
        self.base = base
        self.value=tk.StringVar()

        def thread_it(func):
            t = threading.Thread(target=func)
            t.setDaemon(True)
            t.start()
        self.init_data_proxy_Text = Text(self, width=30, height=20)  # 原始数据录入框
        self.init_data_proxy_Text.grid(row=1, column=0, rowspan=10, columnspan=10, padx=1, pady=0)
        if len(self.base.ip_list) == 0 or self.base.ip_list == [''] or self.base.ip_list[0] == '':
            pass
        else:
            for l in self.base.ip_list:
                aa=(l[0]+':'+l[1]+';'+'\n')
                #result_data_Text.insert(1.0, str(result))
                self.init_data_proxy_Text.insert(1.0,str(aa))
        self.svn_cancel = tk.Button(self, text='文件', width=7, height=2, command=self.cancel)
        self.svn_cancel.grid(row=66, column=0, columnspan=5, pady=10, padx=15)
        self.svn_save = tk.Button(self, text='保存', width=7, height=2, command=lambda: thread_it(self.set_0))
        self.svn_save.grid(row=66, column=6, columnspan=6, pady=10, padx=25)

    def cancel(self):
        if os.path.exists('proxy.conf') == False:
            fb=open('proxy.conf','w',encoding='gbk')
        os.startfile('proxy.conf')
    def set_0(self):
        src_proxy = self.init_data_proxy_Text.get(1.0, END).strip().replace('\n','')
        mm_proxy = re.findall(r'(.*?):(.*?);', src_proxy, re.S)
        self.base.ip_list=mm_proxy
        self.destroy()

    def mess(self):
            self.destroy()
            messagebox.showinfo('提示', '修改成功！')


class Base(tk.Tk):
    def __init__(self):
        super().__init__()
        self.w, self.h = self.maxsize()
        self.a = 1600
        self.b = 695
        self.wm_resizable(False, False)
        self.x = (self.w - self.a) / 2
        self.y = (self.h - self.b) / 2
        self.geometry('%dx%d+%d+%d' % (self.a, self.b, self.x, self.y))
        self.title("备案查询")  # 窗口名
        self.isexists=os.path.exists('proxy.conf')
        self.ip_list = []
        if self.isexists:
            with open('proxy.conf', 'r', encoding='utf8') as IP_L:
                A_L = IP_L.read().replace('\n','')
            self.ip_list = re.findall(r"(.*?):(.*?);", A_L, re.S)


        self.init_data_label = Label(self, text="待处理数据")
        self.init_data_label.grid(row=0, column=4, columnspan=4, padx=0, pady=0)
        self.result_data_label = Label(self, text="未备案")
        self.result_data_label.grid(row=0, column=13, columnspan=3, padx=0, pady=0)
        self.result_data_label = Label(self, text="已备案")
        self.result_data_label.grid(row=0, column=28, columnspan=3, padx=0, pady=0)
        # 文本框
        init_data_Text = Text(self, width=30, height=45)  # 原始数据录入框
        init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10, padx=1, pady=0)
        result_data_Text_no = Text(self, width=40, height=45)  # 处理结果展示
        result_data_Text_no.grid(row=1, column=12, rowspan=13, columnspan=10, padx=1, pady=0)
        result_data_Text = Text(self, width=155, height=45)  # 处理结果展示
        result_data_Text.grid(row=1, column=24, rowspan=13, columnspan=30, padx=1, pady=0)

        def thread_it(func):
            t = threading.Thread(target=func)
            t.setDaemon(True)
            t.start()

        def curl_url():
            result_data_Text.delete(1.0, END)
            result_data_Text_no.delete(1.0, END)
            result_no,result_yes,num_no, num_yes  = [],[],0, 0
            class MyThread(threading.Thread):
                def __init__(self, ip_list,url):
                    super(MyThread, self).__init__()  # 重构run函数必须要写
                    self.headers = {'User-Agent': UserAgent().random}
                    self.ip_list = ip_list

                    self.url_in=url

                def run(self):
                    self.url = 'http://icp.chinaz.com/searchs?hosts=%s' % self.url_in.replace('\n', '')
                    re_get=True
                    while re_get:
                        try:
                            if self.ip_list == ['']  or len(self.ip_list) == 0 or self.ip_list[0] == '':
                                html = requests.get(url=self.url, headers=self.headers)
                                re_get = False
                            else:
                                self.proxy_ip = random.choice(self.ip_list)
                                self.ppp = "http://%s:%s" % (self.proxy_ip[0], self.proxy_ip[1])
                                self.ppps = "https://%s:%s" % (self.proxy_ip[0], self.proxy_ip[1])
                                self.proxies = {'http': self.ppp, 'https': self.ppps}
                                html = requests.get(url=self.url, headers=self.headers, proxies=self.proxies)
                                re_get = False
                        except requests.exceptions.ProxyError:
                            pass
                    html.encoding = "utf8"
                    a = re.findall(r'<tr class=&#x27;bg-list&#x27; (.*?)<td>\r\n                                        <a href=\'javascript:needvip\(\); \' class=\'\'>',html.text, re.S)
                    time= re.findall(r'\r\n                                    </td>\r\n                                <td class="tc">(.*?)</td>\r\n                                <td class="tc">\r\n                                        <a class="UpBtn" href="javascript:" data-host=".*?"></a>',html.text, re.S)
                    b = re.findall(r'data-addrp=".*?" data-have="(.*?)" data-typ=".*?">\r\n', a[0], re.S)
                    c = re.findall(r'<td><a target="_blank" href=".*?">(.*?)</a></td>\r\n', a[0], re.S)
                    d = re.findall(r'<td class="tc">(.*?)</td>\r\n', a[0], re.S)
                    e = re.findall(r'<td>(.*?)</td>\r\n', a[0], re.S)
                    if time==[]:
                        time=['--']

                    if b[0] == '':
                        b[0] = '未备案或备案取消'
                        c.append('未备案或备案取消')
                        result = (c[0]+'  '+'未备案或备案取消'+'\n'+'\n')
                        result_data_Text_no.insert(1.0, str(result))
                        result_no.append(result)
                    else:
                        result = (c[0]+'  '+'主办单位名称:'+c[1]+'  '+'单位性质:'+d[0]+'  '+'备案号:'+e[2]+'  '+'网站名称:'+e[3]+'  '+'审核时间:'+time[0]+'\n'+'\n')
                        result_yes.append(result)
                        result_data_Text.insert(1.0, str(result))

            src = init_data_Text.get(0.0, END).strip().replace('\n','')
            mm = re.findall(r'(.*?);', src, re.S)
            if mm == []:
                mm = src
            for i in mm:
                t1 = MyThread(self.ip_list,i)
                t1.start()

            rrr=True
            while rrr:
                if len(mm) == len(result_yes)+len(result_no):
                    # 输出到界面
                    var=('总查询数:'+ str(len(result_no)+len(result_yes))+ '   '+ '已备案数:'+ str(len(result_yes))+ '  '+ '未备案数:'+ str(len(result_no))+'\n'+'\n')
                    result_data_Text.insert(1.0, str(var))
                    rrr=False
                else:
                    time.sleep(1)

        def paste(func):
            init_data_Text.delete(1.0, END)
            init_data_Text.event_generate('<<Paste>>')
        self.bind("<Button-3>",paste)

        # 按钮
        self.str_trans_to_md5_button = Button(self, text="查询", width=10, height=3,command=lambda: thread_it(curl_url))  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=15, column=24, padx=1, pady=10)
        self.str_trans_to_md5_button = Button(self, text="代理", width=10, height=3,command=lambda: thread_it(self.wait_window(proxy_get(self))))  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=15, column=35, padx=1, pady=10)
Base().mainloop()
